package cn.wolfcode.luowowo.website.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 猫教授
 * @date 2019/8/9 20:21
 */
public abstract class CookieUtil {
    /**
     * cookie续约问题
     * 如果cookie不存在那么返回null
     *
     * @param cookieNmae 要续约的cookie名字
     * @param time       续约的时间,单位为秒
     */
    public static Cookie cookieContract(HttpServletRequest request, String cookieNmae, int time) {
        Cookie ck = CookieUtil.getCookieByName(request, cookieNmae);
        if (ck != null) {
            ck.setMaxAge(time);//单位为秒
            ck.setPath("/");
            return ck;
        } else {
            return ck;
        }
    }

    /**
     * 从请求对象里面的cookie拿出指定名字的cookie
     *
     * @param request 请求对象
     * @return 如果找到返回cookie, 如果没有找到那么返回null
     */
    public static Cookie getCookieByName(HttpServletRequest request, String cookieNmae) {
        Cookie ck = null;
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookieNmae.equals(cookie.getName())) {
                ck = cookie;
            }
        }
        return ck;
    }

    /**
     * 获取登录cookie里面的登录秘钥,
     * @param request 用户请求对象
     * @return 如果没有就为空
     */
    public static String getToken(HttpServletRequest request) {
        Cookie cookie = CookieUtil.getCookieByName(request, "faceTime");
        if (cookie!=null){
            return cookie.getValue();
        }
        return null;
    }
}
